const { ccclass, property } = cc._decorator;

@ccclass
export default class GameNet extends cc.Component {

    private static webSocket: WebSocket = null;
    protected static wsUrl: string = 'ws://localhost:3000/';

    public static connect() {
        GameNet.webSocket = new WebSocket(this.wsUrl);
        GameNet.webSocket.onopen = (e) => {
            cc.log('onopen')
            cc.log(e)
        }
        GameNet.webSocket.onmessage = (e) => {
            cc.log('onmessage')
            GameNet.process(e.data);
        }
        GameNet.webSocket.onclose = (e) => {
            cc.log('onclose')
            cc.log(e)
        }
        GameNet.webSocket.onerror = (e) => {
            cc.log('onerror')
            cc.log(e)
        }
    }

    public static disconnect() {
        GameNet.webSocket.close();
    }

    private static process(data: any) {
        if (typeof data === 'string') {
            data = JSON.parse(data) as Response;
        }
        cc.log(data);
    }

    public static send(event: string, data: any) {
        if (GameNet.webSocket.readyState === WebSocket.OPEN) {
            let request = new Request();
            request.event = event;
            request.data = data;
            let string = JSON.stringify(request);
            GameNet.webSocket.send(string);
        }
    }

}

class Request {
    event: string;
    data: any;
}

class Response {
    event: string;
    data: any;
}